//
//  YCArticlelistViewController.m
//  YCSchool
//
//  Created by gmall on 16/5/9.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  文章 颜值

#import "YCArticlelistViewController.h"
#import "YCArticleCollectionViewCell.h"

#import "YCArticlelistModel.h"
#import "YCCommentModel.h"
#import "YCPraiseModel.h"
#import "YCDespiseModel.h"
#import "YCPraiseView.h"
#import "YCCommentView.h"

@interface YCArticlelistViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,YCArticleCollectionViewCellDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSInteger _currentIndex;
    BOOL _isLoadMoreTribe;
    BOOL _isLoadMoreOnlookers;
}

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *itemArray;
@property (nonatomic, assign) NSInteger messageNum;
@property (nonatomic, strong) NSMutableArray *photosArray;

@property (nonatomic, strong) NSMutableArray *articleArray;//数据

/** 最后一次请求时间  */
@property (nonatomic, strong) NSString *addtime_str;
@end

@implementation YCArticlelistViewController


#pragma mark - 属性获取

- (NSMutableArray *)photosArray
{
    if (!_photosArray)
    {
        _photosArray = [[NSMutableArray alloc]init];
    }
    return _photosArray;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[YCArticleCollectionViewCell class] forCellWithReuseIdentifier:@"articleCollectionViewCell"];
    }
    return _collectionView;
}


- (NSMutableArray *)articleArray
{
    if (!_articleArray)
    {
        _articleArray = [NSMutableArray array];
    }
    return _articleArray;
}

#pragma mark - 生命周期

- (instancetype)init
{
    if (self = [super init])
    {
        
    }
    return self;
}

- (void)dealloc
{
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    [self yc_addBackBarButtonItem];
    self.navigationItem.title = @"状态";
    self.addtime_str = @"1450873324";
    [self makeView];
    self.collectionView.mj_header = [YCRefreshHeader headerWithRefreshingBlock:^{
        [self loadData];
    }];
    [self.collectionView.mj_header beginRefreshing];
}

- (void)makeView
{
    [self.view addSubview:self.collectionView];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.and.left.right.equalTo(self.view);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



- (void)loadData
{
    NSDictionary *params1 = @{
                              @"uid":@"1",
                              @"token":@"6840c3286f6e6393169943fdbb2bf213",
                              @"cpshow":@"1",//显示赞踩,评论
                              @"caddtime":self.addtime_str,
                              
                              };
    [[YCNetworManager shareManager] postWithUrl:YCAPIUserArticlelist params:params1 success:^(NSURLSessionDataTask *task, ServiceResponse *response) {
        
        [YCArticlelistModel yc_setupObjectClassInArray:^NSDictionary *{
            return @{
                     @"comment":[YCCommentModel class],
                     @"praise":[YCPraiseModel class],
                     @"despise":[YCDespiseModel class]
                     };
        }];
        
        NSMutableArray *dataArray = [YCArticlelistModel yc_objectArrayWithKeyValuesArray:response.data];
        for (id obj in dataArray) {
            [self.articleArray addObject:obj];
        }
        [self.collectionView reloadData];
        YCLog(@"%@",dataArray);//模型数组
        YCArticlelistModel *model = dataArray.firstObject;
        self.addtime_str = [NSDate yc_timestampStrWithDateStr:model.addtime_str format:@"yyyy-MM-dd hh:mm:ss"];
        YCLog(@"%@",model.imgs);
        [self.collectionView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        YCLog(@"%@",error.localizedDescription);
        [self.collectionView.mj_header endRefreshing];
    }];

}


#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section
{
    return self.articleArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YCArticlelistModel *model = self.articleArray[indexPath.row];
    
    YCArticleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"articleCollectionViewCell" forIndexPath:indexPath];
    if (indexPath.row == 0) {
        cell.leftView.hidden = NO;
    } else {
        cell.leftView.hidden = YES;
    }
    [cell relodWithArticle:model];
    cell.delegate = self;
    [cell setNeedsUpdateConstraints];
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YCArticlelistModel *model = self.articleArray[indexPath.row];
        
    CGFloat height = [YCArticleCollectionViewCell heightForArticle:model];
        
    return CGSizeMake(kScreenWidth, height);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
        _currentIndex = indexPath.row;
        
        YCArticlelistModel *model = self.articleArray[indexPath.row];
        
        //if ([model.roleType isEqualToString:@"01"])
        {
            //才气
            //            GOBrilliantDetailViewController *vc = [[GOBrilliantDetailViewController alloc]initWithModel:model];
            //            [self.navigationController pushViewController:vc animated:YES];
        }
       // else if ([model.roleType isEqualToString:@"02"])
        {
            //颜值
            //            GOAppearanceDetailViewController *vc = [[GOAppearanceDetailViewController alloc]initWithModel:model];
            //            [self.navigationController pushViewController:vc animated:YES];
        }
}


#pragma mark - YCArticleCollectionViewCellDelegate
// 点击评论小三角
- (void)didArticleWithModel:(YCArticlelistModel *)model cell:(YCArticleCollectionViewCell *)cell touchUpInsideViewWithBUtton:(UIButton *)button
{
    [self didSelectModel:model cell:cell withButton:button];
}

// 点击头像
- (void)didHeadIconButtonTouchUpInside:(YCArticlelistModel *)model
{

}
// 举报
- (void)didReportButtonTouchUpInside:(YCArticlelistModel *)model
{

}

// 点击查看全文
- (void)needToReloadArticleCollectionView:(YCArticleCollectionViewCell *)cell
{

}
// 长按cell文本进来
- (void)didLongPressWithModel:(YCArticlelistModel *)model
{

}


#pragma mark - 自定义方法

- (void)didSelectModel:(YCArticlelistModel *)model cell:(id)cell withButton:(UIButton *)button
{
    YCPraiseView *view = [[YCPraiseView alloc]init];
    [view showWithSendBlock:^(YCPraiseViewSelectItemType praiseViewSelectItemType) {
        
        switch (praiseViewSelectItemType)
        {
            case YCPraiseViewSelectItemTypePraise:
            {
                //赞
//                NSMutableDictionary *params = [@{@"targetType":@"01",
//                                                 @"infoId":model.articleInfoId,
//                                                 @"praiseType":@"01",
//                                                 } mutableCopy];
//                
//                if ([model.praiseFlag isEqualToString:@"1"])
//                {
//                    [[GOWebService service]postAction:GOAPIPraiseInfoDelete params:params success:^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//                        
//                        if (response.success)
//                        {
//                            [SVProgressHUD showSuccessWithStatus:@"取消点赞成功"];
//                            
//                            for (GOPraiseModel *praiseModel in model.praiseList)
//                            {
//                                if ([praiseModel.userId isEqualToString:[GOLoginUser loginUser].userId])
//                                {
//                                    [model.praiseList removeObject:praiseModel];
//                                    break;
//                                }
//                            }
//                            
//                            model.praiseFlag = @"0";
//                            
//                            dispatch_async(dispatch_get_main_queue(), ^{
//                                [view cancelPraiseView];
//                                NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
//                                [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
//                            });
//                        }
//                        
//                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                        
//                    }];
//                }
//                else
//                {
//                    [[GOWebService service]postAction:GOAPIPraiseInfoAdd params:params success:^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//                        
//                        if (response.success)
//                        {
//                            [SVProgressHUD showSuccessWithStatus:@"点赞成功"];
//                            
//                            GOPraiseModel *praiseModel = [[GOPraiseModel alloc]init];
//                            praiseModel.userId = [GOLoginUser loginUser].userId;
//                            praiseModel.nickname = [GOLoginUser loginUser].userNickName;
//                            praiseModel.headPhoto = [GOLoginUser loginUser].userHeadPhoto;
//                            
//                            [model.praiseList addObject:praiseModel];
//                            model.praiseFlag = @"1";
//                            
//                            dispatch_async(dispatch_get_main_queue(), ^{
//                                
//                                [view cancelPraiseView];
//                                NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
//                                [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
//                            });
//                        }
//                        
//                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                        
//                    }];
//                }
            }
                break;
            case YCPraiseViewSelectItemTypeMercy:
            {
                //怜
                
//                NSMutableDictionary *params = [@{@"targetType":@"01",
//                                                 @"infoId":model.articleInfoId,
//                                                 @"praiseType":@"03",
//                                                 } mutableCopy];
//                
//                if ([model.pityFlag isEqualToString:@"1"])
//                {
//                    [[GOWebService service]postAction:GOAPIPraiseInfoDelete params:params success:^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//                        
//                        if (response.success)
//                        {
//                            [SVProgressHUD showSuccessWithStatus:@"取消怜成功"];
//                            
//                            for (GOPraiseModel *praiseModel in model.pityList)
//                            {
//                                if ([praiseModel.userId isEqualToString:[GOLoginUser loginUser].userId])
//                                {
//                                    [model.pityList removeObject:praiseModel];
//                                    break;
//                                }
//                            }
//                            model.pityFlag = @"0";
//                            dispatch_async(dispatch_get_main_queue(), ^{
//                                
//                                [view cancelPraiseView];
//                                NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
//                                [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
//                            });
//                        }
//                        
//                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                        
//                    }];
//                }
//                else
//                {
//                    [[GOWebService service]postAction:GOAPIPraiseInfoAdd params:params success:^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//                        
//                        if (response.success)
//                        {
//                            [SVProgressHUD showSuccessWithStatus:@"点怜成功"];
//                            
//                            GOPraiseModel *pityModel = [[GOPraiseModel alloc]init];
//                            pityModel.userId = [GOLoginUser loginUser].userId;
//                            pityModel.nickname = [GOLoginUser loginUser].userNickName;
//                            pityModel.headPhoto = [GOLoginUser loginUser].userHeadPhoto;
//                            
//                            [model.pityList addObject:pityModel];
//                            model.pityFlag = @"1";
//                            
//                            dispatch_async(dispatch_get_main_queue(), ^{
//                                [view cancelPraiseView];
//                                NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
//                                [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
//                            });
//                        }
//                        
//                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                        
//                    }];
//                }
            }
                break;
            case YCPraiseViewSelectItemTypeComments:
            {
                //回复
                
                YCCommentView *commentView = [[YCCommentView alloc]init];
                [commentView showWithSendBlock:^(NSString *text) {
                    
//                    [SVProgressHUD showWithStatus:@"正在提交"];
                    
//                    @go_weakify(self);
//                    
//                    [[GOWebService service]postAction:GOAPICommentInfoAdd params:@{@"infoId":model.articleInfoId,@"commentContent":text} success:^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//                        
//                        if (response.success)
//                        {
//                            [SVProgressHUD showSuccessWithStatus:@"评论成功"];
//                            
//                            NSError *error;
//                            GOCommentsModel *commentsModel = [[GOCommentsModel alloc]init];
//                            commentsModel = [MTLJSONAdapter modelOfClass:[GOCommentsModel class] fromJSONDictionary:response.data error:&error];
//                            commentsModel.fromUserNickname = [GOLoginUser loginUser].userNickName;
//                            commentsModel.fromUserHeadPhoto = [GOLoginUser loginUser].userHeadPhoto;
//                            [model.commentList addObject:commentsModel];
//                            
//                            if(!error)
//                            {
//                                @go_strongify(self);
//                                if(!self) return;
//                                
//                                dispatch_async(dispatch_get_main_queue(), ^{
//                                    [view cancelPraiseView];
//                                    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
//                                    [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
//                                });
//                            }
//                        }
//                        
//                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                        
//                    }];
                    
                } cancel:^{
                    
                }];
            }
                break;
                
            default:
                break;
        }
    } withView:button];
}


@end
